#!/usr/bin/perl

use strict;
use App::Control;
require 'config.pl';

$|=1;
my $what = shift @ARGV;

my $exec = $::rsspreader_basedir . "/safe_handler.sh";

my $arguments = [$::rsspreader_basedir, $::handler_pidfilename, $::rsspreader_logfilename, $::rsspreader_runlogfilename];

# Check, ob Start des Skriptes unter dem richtigen User erfolgte, sonst Abbruch !
if ($::execution_username && (my $name = getpwuid $>) ne $::execution_username)	
{
	print "You are logged in as $name.\n";
	print "Please log in as ".$::execution_username." (su " . $::execution_username . ") before you try to start $0.\n";
	exit 0;
}

my $ctl = App::Control->new(
   EXEC => $exec,
   ARGS => $arguments,
   PIDFILE => $::handler_pidfilename,
   SLEEP => 1,
   LOOP => 60,
   VERBOSE => 0
);

if ($what eq "start")
{
	if ($ctl->running)
	{
		print "handler.pl already running.\n";
        exit 1;
	}
	else
	{
		print "Starting handler.pl... ";
		$ctl->start;
		if ($ctl->running)
		{
			print "done\n";
            exit 1;
		}
		else
		{
			print "failed\n";
            exit 0;
		}
	}
}
elsif ($what eq "stop")
{
	if ($ctl->running)
	{
		print "Shutting down handler.pl... ";
		$ctl->stop;
		if ($ctl->running)
		{
			print "failed\n";
            exit 0;
		}
		else
		{
			print "done\n";
            exit 1;
		}
	}
	else
	{
		print "handler.pl not running.\n";
        exit 1;
	}
}
elsif ($what eq "restart")
{
	if ($ctl->running)
	{
		print "Shutting down handler.pl... ";
		$ctl->stop;
		if ($ctl->running)
		{
			print "failed\n";
            exit 0;
		}
		else
		{
			print "done\n";
			print "Starting handler.pl... ";
			$ctl->start;
			if ($ctl->running)
			{
				print "done\n";
                exit 1;
			}
			else
			{
				print "failed\n";
                exit 0;
			}
		}
	}
	else
	{
		print "handler.pl not running.\n";	
		print "Starting handler.pl... ";
		$ctl->start;
		if ($ctl->running)
		{
			print "done\n";
            exit 1;
		}
		else
		{
			print "failed\n";
            exit 0;
		}
	}
}
elsif ($what eq "status")
{
	if ( $ctl->running )
	{
		print "handler.pl (pid " . $ctl->pid . ") is running\n";
        exit 1;
	}
	else
	{
		print "handler.pl not running.\n";
        exit 0;   
	}
}
else
{
	print "bad parameter " . $what . ".\n";
	print "Usage: $0 {start|stop|restart|status}\n";
}
